using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Pixeldyne.Core.Text
{
	/// <summary>
	/// String manipulation tools
	/// </summary>
	public class StringTools
	{
		static readonly Regex HtmlRegex = new Regex("<[^>]*>", RegexOptions.Compiled);

		private StringTools() {}

		/// <summary>
		/// Shorten the given string to the maximum length specified adding ".." at the end of the resulting string
		/// </summary>
		/// <param name="text">string to trim</param>
		/// <param name="maxlen">maximum length</param>
		/// <returns>trimmed string</returns>
		public static string ShortenString(string text, int maxlen)
		{
			if (string.IsNullOrEmpty(text))
				return string.Empty;

			if (text.Length > maxlen)
				return text.Substring(0, maxlen-2) + "..";
			else
				return text;
		}

		// http://msmvps.com/ch21st/articles/530.aspx
		/// <summary>
		/// Makes the first character of a string upper-case
		/// </summary>
		/// <param name="text"></param>
		/// <returns></returns>
		public static string TitleString(string text)
		{
			if (string.IsNullOrEmpty(text))
				return string.Empty;

			var result = new StringBuilder("");
			var regMatches = Regex.Matches(text.ToLower(), @"\w+|\W+", RegexOptions.Compiled);

			foreach (Match m in regMatches)
			{
				string x = m.ToString();	
				x = char.ToUpper(x[0]) + x.Substring(1, x.Length-1); 
				result.Append(x);			
			}

			return result.ToString();
		}


		/// <summary>
		/// Removes all HTML tags from the string
		/// </summary>
		/// <param name="htmlString"></param>
		/// <returns></returns>
		public static string RemoveHtml(String htmlString)
		{
			if (htmlString.Length > 4)
				return HtmlRegex.Replace(htmlString, "");

			return htmlString;
		}

		/// <summary>
		/// Checks if the string is in all capitals
		/// </summary>
		/// <param name="text"></param>
		/// <returns>true if only capitals</returns>
		public static bool IsAllCaps(string text)
		{
			if (string.IsNullOrEmpty(text))
				return false;

			return text.Count(t => t >= 65 && t <= 90) >= text.Length / 2;
		}
	}
}
